package com.controller;

/**
 * Created by wlc on 2018/5/5.
 */

import com.entity.Message;
import com.entity.UserMetadata;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.service.MessageOperator;
import com.util.CookieUtil;
import com.util.LocalInformation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


/**
 * 映射消息管理部分
 */
@Controller
@RequestMapping(value = "/messageManager",produces = "text/html;charset=UTF-8")
public class messageManagerController {
    //映射page-frame获取消息数目部分
    @RequestMapping(value = "/getMessageNum",produces = "text/html;charset=UTF-8")
    public void getMessageNum(HttpServletResponse response, HttpServletRequest request) throws IOException{
        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        String projectPath = request.getSession().getServletContext().getRealPath("/");

        String messageNum = MessageOperator.getMessageNum(projectPath,user_cookie_value.split("wlcniubi")[0]);

        PrintWriter out= null;
        out = response.getWriter();
        out.print(messageNum);
        out.flush();
        out.close();
    }

    //映射数据权限申请部分
    @RequestMapping(value = "/dataAuthorityApplication",produces = "text/html;charset=UTF-8")
    public void dataAuthorityApplication(HttpServletResponse response,
                                         HttpServletRequest request,
                                         @RequestParam(value = "authorityTitle")String authorityTitle,
                                             @RequestParam(value = "authorityApplicationStatus")String authorityApplicationStatus) throws IOException {
        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        String projectPath = request.getSession().getServletContext().getRealPath("/");

        Message message = new Message();
        message.dataAuthorityApplication(user_cookie_value.split("wlcniubi")[0],user_cookie_value.split("wlcniubi")[1],authorityTitle,authorityApplicationStatus);
        MessageOperator.sendMessage(projectPath,message);

        PrintWriter out= null;
        out = response.getWriter();
        out.print("true");
        out.flush();
        out.close();
    }

    //映射消息中心部分
    @RequestMapping(value = "/MessageCenter",produces = "text/html;charset=UTF-8")
    public ModelAndView MessageCenter(HttpServletRequest request) throws Exception{
        ModelAndView modelAndView = new ModelAndView();

        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        if (user_cookie_value != null && UserMetadata.OnlineUserId.containsKey(user_cookie_value)){
            UserMetadata.OnlineUserOperatorTime.replace(user_cookie_value, LocalInformation.getTimeID());
            String projectPath = request.getSession().getServletContext().getRealPath("/");

            System.out.println(user_cookie_value.split("wlcniubi")[0] + "     ]]]]]]]]]]]]]]");
            ArrayList<Message> messages = MessageOperator.getAllMessageInfo(projectPath,user_cookie_value.split("wlcniubi")[0]);
            modelAndView.addObject("messages",messages);
            modelAndView.setViewName("Message-Center");
        }else {
            modelAndView.setViewName("login");
        }
        return modelAndView;
    }

    //映射删除指定ID消息部分
    @RequestMapping(value = "/delMessages",produces = "text/html;charset=UTF-8")
    public void delMessages(HttpServletResponse response,
                            HttpServletRequest request,
                            @RequestParam(value = "messageIds")String messageIds) throws IOException{
        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        String projectPath = request.getSession().getServletContext().getRealPath("/");

        ArrayList<String> id_arr = new ArrayList<String>(Arrays.asList(messageIds.split("wlcniubi")));
        MessageOperator.delMessages(projectPath,user_cookie_value.split("wlcniubi")[0],id_arr);

        PrintWriter out= null;
        out = response.getWriter();
        out.print("true");
        out.flush();
        out.close();
    }

    //映射到标记指定ID消息部分
    @RequestMapping(value = "/markMessages",produces = "text/html;charset=UTF-8")
    public void markMessages(HttpServletResponse response,
                            HttpServletRequest request,
                            @RequestParam(value = "messageIds")String messageIds,
                             @RequestParam(value = "markStuatus")String markStuatus) throws IOException{
        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        String projectPath = request.getSession().getServletContext().getRealPath("/");

        ArrayList<String> id_arr = new ArrayList<String>(Arrays.asList(messageIds.split("wlcniubi")));
        switch (markStuatus){
            case "0":MessageOperator.markMessagesRead(projectPath,user_cookie_value.split("wlcniubi")[0],id_arr);break;
        }

        PrintWriter out= null;
        out = response.getWriter();
        out.print("true");
        out.flush();
        out.close();
    }

    //映射获取指定ID消息部分
    @RequestMapping(value = "/getMessage",produces = "text/html;charset=UTF-8")
    public void getMessage(HttpServletResponse response,
                             HttpServletRequest request,
                             @RequestParam(value = "messageId")String messageId) throws IOException{
        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        String projectPath = request.getSession().getServletContext().getRealPath("/");

        Message message = MessageOperator.getMessageById(projectPath,user_cookie_value.split("wlcniubi")[0],messageId);

        PrintWriter out= null;
        out = response.getWriter();

        out.print(StringUtils.join(message.messageToList().toArray(),"wlcniubi"));
        out.flush();
        out.close();
    }

    /**
     * 获取图片目录集合
     * @param response
     * @param request
     * @param messageId
     * @throws IOException
     */
    @RequestMapping(value="/getMessageImg")
    public void getImagePath(HttpServletResponse response,
                             HttpServletRequest request,
                             @RequestParam("messageId") String messageId) throws IOException {

        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        String projectPath = request.getSession().getServletContext().getRealPath("/");
        String userId = user_cookie_value.split("wlcniubi")[0];

        ArrayList<String> ImgName = MessageOperator.getMessageImageById(projectPath, userId, messageId);  //该消息下所有图片名称

        Map<String,Map<String, String>> ImgInfo = new HashMap<>();

        int len = ImgName.size();
        for(int i = 0; i < len; i++) {
            Map<String, String> temp = new HashMap<>();
            temp.put("userId",userId);
            temp.put("messageId",messageId);
            temp.put("ImgName", ImgName.get(i));
            ImgInfo.put("Img"+i, temp);
        }

        ObjectMapper mapper = new ObjectMapper();

        String ImgJson = mapper.writeValueAsString(ImgInfo);

        PrintWriter out = null;
        out = response.getWriter();
        out.print(ImgJson);
        out.flush();
        out.close();
    }

    /**
     * 显示图片
     * @param request
     * @param response
     * @param userId
     * @param messageId
     * @param ImgName
     * @throws IOException
     */
    @RequestMapping(value="/showImage/{userId}/{messageId}/{ImgName}")
    public void showImageMessage(HttpServletRequest request,
                                 HttpServletResponse response,
                                 @PathVariable String userId,
                                 @PathVariable String messageId,
                                 @PathVariable String ImgName) throws IOException {
        String projectPath = request.getSession().getServletContext().getRealPath("/");
        String filePath = projectPath + "/file_data/message/" + userId + "/" + messageId + "/" + ImgName;
        String prefix = ImgName.substring(ImgName.lastIndexOf(".") + 1);

        File file = new File(filePath);

        if (file.exists()) {


            FileInputStream in = new FileInputStream(file);
            int available = in.available();         //可读byte数
            byte[] input = new byte[available];
            in.read(input);
            in.close();

            String str = new String(input);
            System.out.println(str + "&&&&&&&&&&&&&&&&&&&&");

            response.setCharacterEncoding("UTF-8");
            response.setContentType("image/"+prefix);
            OutputStream out = new BufferedOutputStream(response.getOutputStream());

            out.write(input);
            out.flush();
            out.close();
        }
    }



    //映射到问题反馈页面
    @RequestMapping(value = "/UserFeedback",produces = "text/html;charset=UTF-8")
    public ModelAndView UserFeedback(HttpServletRequest request) throws Exception{
        ModelAndView modelAndView = new ModelAndView();

        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        if (user_cookie_value != null && UserMetadata.OnlineUserId.containsKey(user_cookie_value)){
            UserMetadata.OnlineUserOperatorTime.replace(user_cookie_value, LocalInformation.getTimeID());

            modelAndView.setViewName("User-Feedback");
        }else {
            modelAndView.setViewName("login");
        }
        return modelAndView;
    }

    //映射到问题反馈提交
    @RequestMapping(value = "/FeedbackSubmit",produces = "text/html;charset=UTF-8")
    public ModelAndView FeedbackSubmit(@RequestParam(value="files[]", required = false) CommonsMultipartFile[] input_files, HttpServletRequest request, Message message) throws Exception{
        ModelAndView modelAndView = new ModelAndView();

        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        if (user_cookie_value != null && UserMetadata.OnlineUserId.containsKey(user_cookie_value)){
            UserMetadata.OnlineUserOperatorTime.replace(user_cookie_value, LocalInformation.getTimeID());
            String projectPath = request.getSession().getServletContext().getRealPath("/");

            //反馈信息
            message.FeedBackMessage(user_cookie_value.split("wlcniubi")[0],user_cookie_value.split("wlcniubi")[1]);
            MessageOperator.sendMessage(projectPath,message);
            //附件
            if(input_files != null) {
                for(CommonsMultipartFile input_file :input_files) {
                    String file_path = projectPath + "/file_data/message/" + message.getReceiverId() + "/" + message.getId() + "/" + input_file.getOriginalFilename();
                    File upload_file = new File(file_path);
                    System.out.println(file_path);
                    if(upload_file.exists()) {
                        continue;
                    }
                    input_file.transferTo(upload_file);
                }
            }
            modelAndView.setViewName("SystemHome");
        }else {
            modelAndView.setViewName("login");
        }
        return modelAndView;
    }


    //映射Root用户回复消息部分
    @RequestMapping(value = "/replyMessage",produces = "text/html;charset=UTF-8")
    public void replyMessage(HttpServletResponse response,HttpServletRequest request,Message message) throws IOException{
        String projectPath = request.getSession().getServletContext().getRealPath("/");
        message.replyMessage();
        MessageOperator.sendMessage(projectPath,message);

        PrintWriter out= null;
        out = response.getWriter();
        out.print("true");
        out.flush();
        out.close();
    }
}
